<template>
  <div class="users">
    <Nav :paths="paths"></Nav>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="content">
          <div class="header">
            <div class="find-input">
              <el-input
                placeholder="请输入查找内容"
                v-model="input"
                clearable
              >
              </el-input>
            </div>
            <div class="btn">
              <el-button type="primary" @click="form.isOpenModify = true" round>添加用户</el-button>
            </div>
          </div>
          <h4 class="findMsg">{{ findMsg }}</h4>
        </div>
      </div>
      <div class="text item">

<!--   表格数据   -->

        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            fixed
            prop="username"
            label="用户"
            width="120">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="200">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话"
            width="200">
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色"
            width="120">
          </el-table-column>
          <el-table-column
            prop="mg_state"
            label="状态"
            width="120">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.mg_state"
                @change="stateChange(scope.row.id,scope.row.mg_state)"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="200">
            <template slot-scope="scope">
              <el-button @click="modifyUser(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="deleteUser(scope.row.id)" type="text" size="small">删除</el-button>
              <el-button @click="distribute(scope.row)" type="text" size="small">分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
    <!--   表格数据   -->
      </div>
    </el-card>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[4, 5, 6, 7]"
        :page-size="100"
        layout="sizes, prev, pager, next"
        :total="count">
      </el-pagination>
    </div>
    <el-dialog title="修改数据" :visible.sync="form.isOpenModify">
      <el-form :model="form">
        <el-form-item label="用户名称 *" label-width="120px">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码 *" label-width="120px">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="120px">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="form.isOpenModify = false;open('取消创建','info')">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <ModifyUser :data="modifyData" v-if="isModify"></ModifyUser>
    <AssignUser ref="Assign"/>
  </div>
</template>

<script lang="ts">
import {
  ADD_USER,
  DELETE_USER,
  FIND_USER,
  GET_ALL_ROLES,
  GET_PAGE_USER,
  UPDATE_PAGE_NUM,
  UPDATE_PAGE_SIZE
} from '@/store/user/CONST'
import { Vue, Component, Watch } from 'vue-property-decorator'
import { createNamespacedHelpers } from 'vuex'
import { addUser, getAllRoles, updateState } from '@/api/user'
import ModifyUser from '@/components/Modify_Users.vue'
import AssignUser from '@/components/Assign_user.vue'
import Nav, { paths } from '@/components/Nav'
import { GET_ROUTES } from '@/store/public/CONST'

const { mapGetters, mapActions, mapState } = createNamespacedHelpers('user')
@Component({
  components: { Nav, ModifyUser, AssignUser },
  methods: {
    ...mapActions([])
  },
  computed: {
    ...mapState(['count']),
    ...mapState(['user'])
  }
})

export default class users extends Vue {
  constructor (...arg:any) {
    super(...arg)
    getAllRoles().then(({ data: { data: res } }) => {
      this.$store.commit('user/' + GET_ALL_ROLES, res)
    })
  }

  private loading = true
  public paths:paths = [
    { path: '/index', pName: '首页' },
    { path: '/index/users', pName: '用户管理' },
    { path: '/index/users', pName: '用户列表' }
  ]

  @Watch('$store.state.user.userArr')
  _update1 () {
    this.loading = false
  }

  public input = ''
  public inputTimer = 0
  public findMsg = '输入名字查找'

  public get currentPage () {
    return this.$store.state.user.pageNum
  }

  public get pageSize () {
    return this.$store.state.user.pageSize
  }

  public get tableData () {
    return this.$store.state.user.userArr
  }

  public form= {
    username: '',
    password: '',
    email: '',
    mobile: '',
    isOpenModify: false
  }

  public isModify = false
  public modifyData = {}

  async addUser () {
    if (!this.form.username || !this.form.password) return this.open('请填写用户名密码', 'warning')
    if (!/^[a-zA-Z]\w{2,8}$/.test(this.form.username)) return this.open('用户名必须为首字母大写共由3-9位字母数字组成', 'error')
    if (!/^\w{6,16}/.test(this.form.password)) return this.open('密码由字母数字下划线组成共6-16位')
    const data = { ...this.form }
    const { data: resData, meta } = await addUser({
      username: data.username,
      password: data.password,
      email: data.email,
      mobile: +data.mobile
    })
    if (meta.status !== 201) return this.open(meta.msg, 'warning')
    this.open(meta.msg, 'success')
    this.form.username = ''
    this.form.password = ''
    this.form.email = ''
    this.form.mobile = ''
    this.form.isOpenModify = false
    this.render1()
  }

  @Watch('input', { })
  findInputWatch (newVal:string) {
    clearTimeout(this.inputTimer)
    this.findMsg = '正在输入'
    this.inputTimer = setTimeout(() => {
      if (!newVal) {
        this.render1()
        return (this.findMsg = '输入名字查找')
      }
      this.findMsg = '搜索中'
      setTimeout(() => {
        this.$store.dispatch('user/' + FIND_USER, this.input)
        this.$nextTick(() => {
          this.findMsg = '找到' + this.$store.state.user.userArr.length + '条数据'
        })
      }, Math.random() * 1000)
    }, 1000)
  }

  public get findName () {
    return this.$store.state['user/findName']
  }

  // 显示数据条数发生变化
  handleSizeChange (e:number) {
    this.$store.commit('user/' + UPDATE_PAGE_SIZE, e)
    this.render1()
  }

  // 点击分页出发
  handleCurrentChange (e:number) {
    this.$store.commit('user/' + UPDATE_PAGE_NUM, e)
    this.render1()
  }

  // 更新页面
  render1 () {
    this.$nextTick(() => {
      this.loading = true
      this.$store.dispatch('user/' + GET_PAGE_USER)
    })
  }

  currentPage2 (e:number) {
    //
  }

  // 单击编辑按钮
  modifyUser (e:any) {
    this.modifyData = e
    this.isModify = true
  }

  async deleteUser (id:number) {
    try {
      await this.$confirm('此操作将会删除该用户, 是否继续?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await this.$store.dispatch('user/' + DELETE_USER, id)
      this.open('删除成功', 'success')
      this.render1()
    } catch (error) {
      this.open('取消删除', 'warning')
    }
  }

  distribute (e:any) {
    console.log(e)
    const assign = (this.$refs.Assign as any)
    assign.isOpen = true
    assign.currentName = e.username
    assign.currentRole = e.role_name
    assign.currentId = e.id
  }

  // 提示框
  open (
    smg = '登陆成功',
    type: 'success' | 'warning' | 'info' | 'error' = 'success'
  ) {
    this.$message({
      message: smg,
      type: type
    })
  }

  mounted () {
    // console.log(this.tableData)
  }

  created () {
    this.$store.dispatch(GET_ROUTES)
    this.$store.dispatch('user/' + GET_PAGE_USER)
    this.$root.$on('modifyData', (done:boolean) => {
      if (done) {
        this.render1()
      }
      this.isModify = false
    })
  }

  // 单击状态开关
  async stateChange (id:number, state:boolean) {
    const { meta } = await updateState(id, !state)
    this.open(meta.msg, meta.status === 200 ? 'success' : 'error')
    this.render1()
  }
}
</script>

<style lang="less" scoped>
.users {
  .header{
    overflow: hidden;
    .find-input {
      float: left;
      width: 30%;
    }
    .btn{
      float: left;
      margin: 0px 20px;
    }
  }
  .findMsg{
    margin-top: 10px;
    text-indent: 2em;
  }
  .box-card{
    margin-top: 10px;
    padding-bottom: 20px;
  }
}
</style>
